<template>
  <div class="app-container" style="height: 100%">
    <div class="app-container-inner" style="display: flex; flex-direction: column">
      <!-- 按钮组 & 搜索条件 -->
      <div class="btn-group-search">
        <!-- 搜索条件 -->
        <div style="display: flex; gap: 5px">
          <HPlainButton @click="addEmp">新增商家</HPlainButton>
          <EditStrategyBtn :factory-ids="selectionFactoryList" />
        </div>
        <div class="search">
          <el-input
            class="search-input-name"
            v-model="search.keyword"
            placeholder="商家名称/商家编码/电话/地址"
          />
          <HButton type="primary" @click="requestEmpListApi">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
        </div>
      </div>
      <div class="table" style="flex: 1; position: relative">
        <el-table
          :border="true"
          :data="empList"
          v-loading="loading"
          element-loading-text="加载中..."
          height="100%"
          style="position: absolute"
          @selection-change="handleSelectionChange"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>

          <!--选择-->
          <el-table-column type="selection" width="55" />

          <!-- 序号 -->
          <el-table-column label="序号" type="index" width="50" align="center" />

          <!-- 商家编号 -->
          <el-table-column show-overflow-tooltip label="商家编号" prop="numberNo" min-width="120" />

          <!-- 商家名称 -->
          <el-table-column show-overflow-tooltip label="商家名称" prop="name" min-width="120">
            <template v-slot="i">
              <span class="number" @click="detailPage(i.row)">{{ i.row.name }}</span>
            </template>
          </el-table-column>

          <!-- 商家状态 -->
          <el-table-column show-overflow-tooltip label="商家状态" width="90">
            <template #header>
              <span class="style_condition">商家状态</span>
              <el-popover placement="bottom" :width="80" ref="popoverDom">
                <template #reference>
                  <span class="iconfont icon-shaixuan"></span>
                </template>
                <div class="radios">
                  <el-radio-group v-model="search.status" @change="changeStatus">
                    <el-radio value="">全部</el-radio>
                    <el-radio :value="item.value" v-for="item in options" :key="item.value">
                      {{ item.name }}
                    </el-radio>
                  </el-radio-group>
                </div>
              </el-popover>
            </template>
            <template #default="scope">
              <HStatus type="warning" v-if="scope.row.status === 1">待审核</HStatus>
              <HStatus v-if="scope.row.status === 2">启用</HStatus>
              <HStatus type="error" v-if="scope.row.status === 3">已驳回</HStatus>
              <HStatus type="info" v-if="scope.row.status === 4">已禁用</HStatus>
            </template>
          </el-table-column>
          <!-- 结算类型 -->
          <el-table-column
            show-overflow-tooltip
            label="结算类型"
            prop="settlementTypeStr"
            width="100"
          />
          <el-table-column
            align="right"
            show-overflow-tooltip
            label="可下单金额"
            prop="orderableMoney"
            width="100"
          >
            <template v-slot="i"> ￥{{ (i.row.orderableMoney || 0).toFixed(2) }} </template>
          </el-table-column>

          <!-- 联系人 -->
          <el-table-column show-overflow-tooltip label="联系人" prop="username" width="80" />

          <!-- 联系电话 -->
          <el-table-column show-overflow-tooltip label="联系电话" prop="phone" width="104" />

          <!-- 地址 -->
          <el-table-column
            show-overflow-tooltip
            prop="networkEmpLevel"
            label="地址"
            min-width="130"
          >
            <template v-slot="item">
              {{ item.row.province }}{{ item.row.city }}{{ item.row.area
              }}{{ item.row.town }}&nbsp;{{ item.row.address }}
            </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

          <!-- 操作 -->
          <el-table-column fixed="right" label="操作" width="90">
            <template #default="i">
              <el-space :size="0" :spacer="spacer">
                <HLink @click="editPages(i.row)">编辑</HLink>
                <HLink v-if="i.row.status == 1" @click="checkFactoryType(i.row.id, 1)">审核</HLink>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer">
        <Pagination
          ref="pagination"
          :list_total="total"
          @size-change="requestEmpListApi"
          @current-change="requestEmpListApi"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, h } from 'vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import { getListFactory, checkFactory } from '@/api/merchant'
  import { useRouter, useRoute } from 'vue-router'
  import { Factory } from './types'
  import EditStrategyBtn from './components/EditStrategyBtn/index.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.merchant.merchantList,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, { direction: 'vertical' })

  const router = useRouter()
  const route = useRoute()
  const loading = ref(false) // 动画加载
  const total = ref(0) // 服务人员列表总数量
  const empList = ref<Array<Factory>>([]) // 服务人员列表
  const search = ref({
    // 服务人员搜索对象
    page: 1,
    limit: 50,
    keyword: '', // 关键词搜索：商家名称/商家编码/电话/地址
    status: null,
  })
  const popoverDom = ref()
  // 状态
  const options = [
    { value: 1, name: '待审核' },
    { value: 2, name: '启用' },
    { value: 3, name: '已驳回' },
    { value: 4, name: '已禁用' },
  ]
  // 获取服务人员列表
  const requestEmpListApi = () => {
    loading.value = true
    getListFactory(search.value).then((res) => {
      loading.value = false
      if (!res.data.success) {
        if (res.data.isError) ElMessage.error(res.data.message)
      }
      total.value = Number(res.data?.data.total)
      empList.value = res.data?.data.rows
    })
  }
  // 状态变化
  const changeStatus = () => {
    requestEmpListApi()
    popoverDom.value.hide()
  }

  // 新增工程师
  const addEmp = () => {
    router.push('/merchant/new')
  }
  // 详情
  const detailPage = (row) => {
    router.push(`/merchant/listdetail/${row.id}`)
  }
  // 编辑
  function editPages(row) {
    if (row) {
      router.push(`/merchant/newdetail/${row.id}`)
    }
  }
  const checkFactoryType = (id, type) => {
    ElMessageBox({
      title: '提示',
      message: type == 1 ? `确认审核通过?` : '确认驳回？',
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    })
      .then(() => {
        checkFactory(id, type).then((res) => {
          if (res.data.success) {
            requestEmpListApi()
          }
          if (res.data.isError)
            ElMessage({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
            })
        })
      })
      .catch(() => {
        // 取消按钮被点击了
      })
  }

  // 被选中的列
  const selectionFactoryList = ref<Array<string>>([])

  // 表格多选事件
  const handleSelectionChange = (factoryList: Array<Factory>) => {
    selectionFactoryList.value = factoryList.map((factory) => factory.id)
  }

  onMounted(() => {
    requestEmpListApi()
  })

  watch(
    () => route.name,
    (value) => {
      if (value === 'list') {
        requestEmpListApi()
      }
    },
  )
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
